/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kmcsoft.goldshop.importdiamond;

import com.kmcsoft.comp.ImageUploadComp;
import com.kmcsoft.core.ui.GenericController;
import com.kmcsoft.goldshop.generic.service.ShopGenericService;
import com.kmcsoft.goldshop.importdiamond.service.ImportDiamondService;
import com.kmcsoft.goldshop.model.master.Booth;
import com.kmcsoft.goldshop.model.master.DiamondColor;
import com.kmcsoft.goldshop.model.master.DiamondGroup;
import com.kmcsoft.goldshop.model.master.DiamondPure;
import com.kmcsoft.goldshop.model.master.ProductDiamond;
import com.kmcsoft.goldshop.model.master.ProductStatusHistory;
import com.kmcsoft.goldshop.model.master.Shop;
import com.kmcsoft.goldshop.model.scm.ImportJewelryDetail;
import com.kmcsoft.goldshop.model.scm.ImportJewerlyOrder;
import com.kmcsoft.utils.DateUtil;
import com.kmcsoft.zkex.PagingListModel;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Doublebox;
import org.zkoss.zul.Window;

/**
 *
 * @author huyvu
 */
public class ImportDiamondComposer extends GenericController<ProductDiamond, ImportDiamondService> {

    private Collection<Booth> booths;
    private Combobox boothCbx;
    private ImportJewerlyOrder importOrder;
    private long empId;
    @Autowired
    ShopGenericService shopGenericService;
    private Combobox diamondColorCbx;
    private Combobox diamondGroupCbx;
    private Combobox diamondPureCbx;

    //<editor-fold defaultstate="collapsed" desc="GET/SET">
    public Collection<DiamondColor> getDiamondColors() {
        return shopGenericService.getDiamondColors();
    }

    public Collection<DiamondGroup> getDiamondGroups() {
        return shopGenericService.getDiamondGroups();
    }

    public Collection<DiamondPure> getDiamondPures() {
        return shopGenericService.getDiamondPures();
    }

    public Collection<Booth> getBooths() {
        return booths;
    }

    public ImportJewerlyOrder getImportOrder() {
        return importOrder;
    }

    public void setImportOrder(ImportJewerlyOrder importOrder) {
        this.importOrder = importOrder;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="doAfterCompose">
    @Override
    public void doAfterCompose(Component comp) throws Exception {
        super.doAfterCompose(comp);
        empId = service.getEmployee().getId();
        booths = shopGenericService.getBooths();
        importOrder = shopGenericService.getImportOrderByEmployeeId(empId, new Date(), ImportJewerlyOrder.TYPE_DIAMOND);
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="PagingListModel">
    @Override
    public PagingListModel getListModel() {
//        PagingListModel<ProductDiamond> model = Utilities.getPagingListModel(objectClass, HashMap.class, "id, status ,createdDate, barcode, productType");
        PagingListModel<ProductDiamond> model = super.getListModel();
        if (model != null) {

            model.setFilter("productType == pType");
            model.setParameters("java.lang.Integer pType");
            model.setParameterValues(Integer.valueOf(ProductDiamond.TYPE_DIAMOND));
        }
        model.setOrdering("createdDate descending");
        model.initialize();
        return model;
    }

    @Override
    public void setSelected(ProductDiamond selected) {
        importOrder = shopGenericService.getImportJewerlyOrderByProductId(selected.getId());
        super.setSelected(service.getProductDiamondById(selected.getId()));
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="onCreate">
    public void onCreate() {
        onClick$new(null);
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="doAfterNew">
    @Override
    protected void doAfterNew() {
        super.doAfterNew();
        setValue();
        if (importOrder.isClosed()) {
            importOrder = shopGenericService.getImportOrderByEmployeeId(empId, new Date(), ImportJewerlyOrder.TYPE_DIAMOND);
        }
        loadPicture();
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="doBeforeSave">
    @Override
    protected void doBeforeSave() {
        super.doBeforeSave();
        saveImage();
        ProductStatusHistory history = new ProductStatusHistory(selected.getStatus());
        service.makePersistent(history);
        selected.getStatusHistoryProducts().add(history);
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="doAfterSave">
    @Override
    protected void doAfterSave() {
        super.doAfterSave();
        super.setSelected(service.getProductDiamondById(selected.getId()));
        if (importOrder.getId() == 0) {
            importOrder.setCode(shopGenericService.createOrderCode());
            service.makePersistent(importOrder);
            importOrder = shopGenericService.getImportJewerlyOrderById(importOrder.getId());
        }
        if (selected.getImportJewelryDetail() == null) {
            ImportJewelryDetail detail = new ImportJewelryDetail(selected.getUnit(), selected.getCurrency().getBuyingPrice());
            service.makePersistent(detail);
            detail = shopGenericService.getImportJewerlyDetailById(detail.getId());

            selected.setImportJewelryDetail(detail);
            detail.setProduct(selected);
            detail.setOrder(importOrder);
            importOrder.getDetails().add(detail);
            service.makePersistent(importOrder);
        }

    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="isVisibledFinishButton">
    public boolean isVisibledFinishButton() {
        if (readonly) {
            if (importOrder.getId() != 0) {
                if (importOrder.getCreatedDate().before(DateUtil.beginOfDate(new Date()))) {
                    return false;
                }
            }
            return !importOrder.isClosed();
        } else {
            return readonly;
        }
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="onClick$finish">
    public void onClick$finish(ForwardEvent event) {
        importOrder.setClosed(true);
        service.makePersistent(importOrder);
        getBinder().loadComponent(event.getOrigin().getTarget().getParent());
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("importOrderId", importOrder.getId());
            Window win = (Window) Executions.createComponents("/shop/modal/diamondOrderInformation.zul", null, map);
            win.doModal();
        } catch (Exception ex) {
            log.error("ERROR from onClick$finfish", ex);
        }
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="onSelect$leftList">
    public void onSelect$leftList() {
        loadPicture();
    }
    //</editor-fold>
    //<editor-fold defaultstate="collapsed" desc="uploadImgs">
    private ImageUploadComp imageUpload;

    public void loadPicture() {
        if (selected.getPicture() != null) {
            imageUpload.getImage().setSrc(selected.getPicture());
        } else {
            imageUpload.getImage().setSrc(imageUpload.getBlankAvatarPath());
        }
    }

    public void saveImage() {
        if (selected.getPicture() != null) {
            if (imageUpload.getFileToDelete() != null && imageUpload.getMedia() == null) {
                imageUpload.saveImage();
                selected.setPicture(null);
            } else if (imageUpload.getMedia() != null) {
                imageUpload.saveImage();
                selected.setPicture(imageUpload.getPathFile());
            }
        } else if (imageUpload.getMedia() != null && selected.getPicture() == null) {
            imageUpload.saveImage();
            selected.setPicture(imageUpload.getPathFile());
        }
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="onLoadBooth">
    public void onLoadBooth(ForwardEvent event) {
        Shop shop = (Shop) ((Combobox) event.getOrigin().getTarget()).getSelectedItem().getValue();
        booths = shop.getBooths();
        getBinder().loadComponent(boothCbx);
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="setValue">
    private void setValue() {
        ProductDiamond rencent = (ProductDiamond) service.getRecentProduct(new Date(), empId);
        if (rencent != null) {
            selected.setCode(rencent.getCode());
            selected.setCurrency(rencent.getCurrency());
            selected.setCost(rencent.getCost());
            selected.setName(rencent.getName());
            selected.setPicture(rencent.getPicture());
            selected.setProductType(rencent.getProductType());
            selected.setStatus(rencent.getStatus());
            selected.setUnit(rencent.getUnit());
            selected.setCostCurrency(rencent.getCostCurrency());
            selected.setCostCurrencyExchange(rencent.getCostCurrencyExchange());
        } else {
            selected.setCurrency(shopGenericService.getBasicCurrency());
            selected.setUnit(shopGenericService.getUnitByCode("3"));
            selected.setStatus(ProductDiamond.STATUS_INSTOCK);
            selected.setProductType(ProductDiamond.TYPE_DIAMOND);
            selected.setCostCurrency(shopGenericService.getCurrencyByCode("USD"));
            selected.setCostCurrencyExchange(selected.getCostCurrency().getBuyingPrice());

        }
        selected.setBarcode(shopGenericService.getBarCode());
    }
//</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="onAddDiamondGroup">
    public void onAddDiamondGroup(ForwardEvent event) {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("binder", getBinder());
            map.put("component", diamondGroupCbx);
            Window win = (Window) Executions.createComponents("/shop/modal/diamondGroupModal.zul", null, map);
            win.doModal();
        } catch (Exception ex) {
            log.error("ERROR from onAddDiamondGroup", ex);
        }
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="onAddDiamondColor">
    public void onAddDiamondColor(ForwardEvent event) {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("binder", getBinder());
            map.put("component", diamondColorCbx);
            Window win = (Window) Executions.createComponents("/shop/modal/diamondColorModal.zul", null, map);
            win.doModal();
        } catch (Exception ex) {
            log.error("ERROR from onAddDiamondPure", ex);
        }
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="onAddDiamondPure">
    public void onAddDiamondPure(ForwardEvent event) {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("binder", getBinder());
            map.put("component", diamondPureCbx);
            Window win = (Window) Executions.createComponents("/shop/modal/diamondPureModal.zul", null, map);
            win.doModal();
        } catch (Exception ex) {
            log.error("ERROR from onAddDiamondPure", ex);
        }
    }
    //</editor-fold>
    
    public void  onCalculateCost(ForwardEvent event){
        Doublebox costCurrencyExchange=(Doublebox)event.getOrigin().getTarget().getFellow("costCurrencyExchangeDbx");
        Doublebox cost=(Doublebox)event.getOrigin().getTarget().getFellow("costDbx");
        Doublebox costInBasicCurrency=(Doublebox)event.getOrigin().getTarget().getFellow("costInBasicCurrencyDbx");
        costInBasicCurrency.setValue(cost.doubleValue()*costCurrencyExchange.doubleValue());
    }
}
